package com.jfsnpm.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.matchers.GroupMatcher;
import org.snaker.engine.SnakerException;

import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Magic;
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.feature.MagicType;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Line;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfsnpm.action.PmMenu;
import com.jfsnpm.common.AppSql;
import com.jfsnpm.common.AppTool;
import com.jfsnpm.plugin.bjui.Bjui;
import com.jfsnpm.plugin.bjui.BjuiRender;
import com.jfsnpm.plugin.jfinal.excel.PoiRender;
import com.jfsnpm.plugin.snakerflow.FlowReminder;
import com.jfsnpm.plugin.snakerflow.QuartzPlugin;
import com.jfsnpm.plugin.snakerflow.TestJob;

public class TestController extends Controller {
	public void session() {
		render(BjuiRender.timeout());
	}

	public void getauth() {

	}

	public void echarts() {

	}

	public void echartsjson() {
		// 测试echart java类
		GsonOption option = new GsonOption();
		option.title().text("菜单点击量统计").textStyle().fontFamily("Verdana");
		option.toolbox()
				.show(true)
				.feature(
						// Tool.mark,
						Tool.dataView, new MagicType(Magic.line, Magic.bar),
						Tool.restore, Tool.saveAsImage);
		option.tooltip();
		option.legend("菜单点击量");
		option.yAxis(new ValueAxis());
		CategoryAxis xaxis = new CategoryAxis();
		List<String> x = new ArrayList<String>();
		List<Long> y = new ArrayList<Long>();
		Line line = new Line();
		List<Record> datas = Db.find(AppSql.getsql("Index.menucount"));
		for (Record data : datas) {
			x.add(data.get("logdate").toString());
			y.add(Long.parseLong(data.get("logcount").toString()));
		}
		xaxis.data(x.toArray());
		option.xAxis(xaxis);
		line.name("菜单点击量").data(y.toArray());
		option.series(line);
		// setAttr("option", option.toString());
		renderJson(option.toString());
	}

	public void testprint() {

	}

	public void autoredirect() {
		setAttr("testtext", "autoredirect");
		Bjui.BjuiReloadUrl(this, "../Test/autoredirect2", "测试标题");
	}

	public void autoredirect2() {
		setAttr("testtext", "autoredirect2");
	}

	public void excel_view() {

	}

	public void excel() {
		List<Record> conList = Db.find("select * from pm_user");
		PoiRender excel = new PoiRender(conList);
		String[] columns = { "id", "no", "name", "status", "createtime",
				"expirytime" };
		String[] heades = { "编号", "工号", "姓名", "状态", "建立日期", "到期日期" };
		render(excel.fileName("用户列表.xls").sheetName("所有").headers(heades)
				.columns(columns));
	}

	public void menu() {
		setAttr("menulist", PmMenu.getAllMenu());
	}

	public void largeData() {
		Bjui.BjuiPageByTableName("pm_log", this);
	}

	public void other() {
		/*String filesystem = "/var/vcap/store/fss_backend1/af5dc1b9-e18b-401d-8cef-55378a553013/";
		String path = filesystem;
		File fileDir = new File(path);
		if (fileDir.isDirectory()) {
			try {
				showAllFiles(fileDir);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("*********Not a Directory!");
		}*/
		
	}
	public void other_get(){
		//renderJson(Db.find("select * from pm_user"));
		try {
			Scheduler sc = QuartzPlugin.getScheduler();
			Set<JobKey> keys = sc.getJobKeys(GroupMatcher.anyJobGroup());
			List<Map<String,String>> joblist = new ArrayList<Map<String,String>>();
			for(JobKey jk:keys){
				Map<String,String> map = new HashMap<String, String>();
				JobDetail job = sc.getJobDetail(jk);
				List<? extends Trigger> tlist = sc.getTriggersOfJob(jk);
				for(Trigger tg:tlist){
					map.put("jobGroup", jk.getGroup());
					map.put("jobName", jk.getName());
					map.put("jobClass", job.getJobClass().getName());
					map.put("triggerGroup", tg.getKey().getGroup());
					map.put("triggerName", tg.getKey().getName());
					map.put("triggerType", tg.getClass().getSimpleName());//触发器类型
					
					map.put("triggerNextFireTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tg.getNextFireTime()));
					
					if(tg instanceof SimpleTrigger){
						SimpleTrigger tgs = ((SimpleTrigger)tg);
						map.put("triggerSimpleRepeatCount", tgs.getRepeatCount()+"");
						map.put("triggerSimpleRepeatInterval", (tgs.getRepeatInterval()/1000)+"");
					}
					if(tg instanceof CronTrigger){
						CronTrigger tgs = ((CronTrigger)tg);
						map.put("triggerCronExpression", tgs.getCronExpression());
					}
					joblist.add(map);
				}
			}
			System.out.println(joblist);
			renderJson(joblist);
		} catch (SchedulerException e) {
			throw new SnakerException(e);
		}
		
	}
	public void other_delete(){
		render(BjuiRender.success("保持成功", false));
		try {
			Scheduler sc = QuartzPlugin.getScheduler();
			JobDetail job = JobBuilder.newJob(TestJob.class)
			        .withIdentity(AppTool.getUUID(), "group1")
			        .build();

			    // Trigger the job to run now, and then repeat every 40 seconds
			    Trigger trigger = TriggerBuilder.newTrigger()
			        .withIdentity(AppTool.getUUID(), "group1")
			        .startNow()
			        .withSchedule(SimpleScheduleBuilder.simpleSchedule()
			                .withIntervalInSeconds(60)
			                .repeatForever())            
			        .build();
			    // Tell quartz to schedule the job using our trigger
			    sc.scheduleJob(job, trigger);
		} catch (SchedulerException e) {
			throw new SnakerException(e);
		}
	}
	public void other_save(){
		render(BjuiRender.success("测试保存失败", false));
		
		
	}

	final static void showAllFiles(File dir) throws Exception {
		File[] fs = dir.listFiles();
		for (int i = 0; i < fs.length; i++) {
			System.out.println(fs[i].getAbsolutePath());
			if (fs[i].isDirectory()) {
				try {
					showAllFiles(fs[i]);
				} catch (Exception e) {
				}
			}
		}
	}

}
